// services/fileService.js

import fs from "fs";
import path from "path";
import crypto from "crypto";
import File from "../models/File.js";

const uploadDir = path.resolve('uploads');
console.log(uploadDir);

// 确保上传目录存在
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

export const calculateMD5 = (filePath) => {
  return new Promise((resolve, reject) => {
    const hash = crypto.createHash("md5");
    const input = fs.createReadStream(filePath);

    input.on("data", (data) => {
      hash.update(data);
    });

    input.on("end", () => {
      resolve(hash.digest("hex"));
    });

    input.on("error", (err) => {
      reject(err);
    });
  });
};

export const uploadFile = async (file) => {
  const oldPath = file.filepath; // 上传临时路径
  // 计算文件的 MD5 值
  const md5Hash = await calculateMD5(oldPath);
  // 通过MD5值查询数据库中是否存在相同文件
  const existingFile = await File.findOne({ where: { md5_hash: md5Hash } });
  if (existingFile) {
    console.log("文件已存在，返回已存在的文件信息");
    return existingFile;
  }
  console.log(md5Hash);
  // 新路径
  const newPath = path.join(
    uploadDir,
    `${md5Hash}.${file.originalFilename.split(".")[1]}`
  );

  // 移动文件
  await new Promise((resolve, reject) => {
    fs.rename(oldPath, newPath, (err) => {
      if (err) {
        reject(new Error("Error saving file"));
      } else {
        resolve();
      }
    });
  });

  console.log(file.originalFilename);
  // 创建文件记录
  const newFile = await File.create({
    file_name: `${md5Hash}.${file.originalFilename.split(".")[1]}`,
    file_url: `https://api.dqh.baby/uploads/${md5Hash}.${
      file.originalFilename.split(".")[1]
    }`,
    file_type: file.mimetype,
    file_size: file.size,
    md5_hash: md5Hash,
    created_at: new Date(),
    updated_at: new Date(),
  });

  return newFile;
};
